//
//  OAuthViewController.swift
//  波波微博
//
//  Created by wave on 15/7/30.
//  Copyright © 2015年 wave. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {

    
    //MARK: - 搭建界面
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
        
        title = "新浪微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    func close(){
        
        SVProgressHUD.dismiss()
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl()))
        
    }
    
    //MARK: - WebView的代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        
        //开启一个转轮
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        //关闭一个转轮
        SVProgressHUD.dismiss()
    }

    ///网络2
    /**
        1.如果请求的URL包含回调地址,需要判断参数,否则继续加载
        2.如果请求参数中,包含code,可以从请求的url中获得请求码
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获取一个完整的字符串
        let urlString = request.URL!.absoluteString
        
        //判断是否包含回调地址
        if !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri){
            
            return true
        }
        
        print("判断参数")
        print(request.URL?.query)   //输出code后边的授权码
        
        if let query = request.URL?.query where query.hasPrefix("code="){

            print("获取授权码")
            
            //从query中截取授权码
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            
            //TODO: - 换取TOKEN
            loadAccessToken(code)
            
            print(code)

       }
        else
        {
            close()
        }
        
        return false
    }

    //传递code(授权码)方法
    private func loadAccessToken(code:String){
        
                                                    //在这里result就会被回调过来
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            
            if error != nil || result == nil{
            
                self.netError()
                
                return
            }
            
            //字典转模型
            /*
                ①.用token获取的信息创建用户账户模型
                ②.异步加载用户信息,保存用户信息(要在模型中完成)
            */
            //MARK: - 此处能执行到
            UserAccount(dict: result!).loadUserInfo({ (error) -> () in
                
                if error != nil{
                    
                    self.netError()
                    
//                    return
                }
                
                //MARK:- 跳转
                NSNotificationCenter.defaultCenter().postNotificationName(BBBSwitchMainInterfaceNotification, object: false)

                print("OK")
            })
            
        }
        
    }
 
    //网络出错处理
    private func netError(){
    
        SVProgressHUD.showInfoWithStatus("您的网路不给力")
        
        //延迟一段时间再关闭
        let when = dispatch_time(DISPATCH_TIME_NOW,Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
            
            self.close()
        })
    }
}






















































































